#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cjson/cJSON.h"

char* read_file(const char *filename) {
  FILE *file = fopen(filename, "rb");
  if (!file) {
    perror("Failed to open file");
    return NULL;
  }

  fseek(file, 0, SEEK_END);
  long length = ftell(file);
  fseek(file, 0, SEEK_SET);

  char *buffer = (char*)malloc(length + 1);
  if (!buffer) {
    fclose(file);
    perror("Memory allocation failed");
    return NULL;
  }

  size_t read_len = fread(buffer, 1, length, file);
  if (read_len != length) {
    free(buffer);
    fclose(file);
    perror("Failed to read file");
    return NULL;
  }

  buffer[length] = '\0';
  fclose(file);
  return buffer;
}

int main(int argc, char *argv[]) {
  if (argc < 2) {
    printf("Usage: %s <json_file>\n", argv[0]);
    return EXIT_FAILURE;
  }

  // 1. 读取文件
  char *json_string = read_file(argv[1]);
  if (!json_string) {
    return EXIT_FAILURE;
  }

  // 2. 解析JSON
  cJSON *json = cJSON_Parse(json_string);
  free(json_string);

  if (!json) {
    const char *error_ptr = cJSON_GetErrorPtr();
    if (error_ptr) {
      fprintf(stderr, "Error before: %s\n", error_ptr);
    }
    return EXIT_FAILURE;
  }

  // 3. 提取age字段
  cJSON *age_item = cJSON_GetObjectItemCaseSensitive(json, "age");
  if (age_item && cJSON_IsNumber(age_item)) {
    int age = age_item->valueint;  // 提取整数值
    double age_double = age_item->valuedouble;  // 提取浮点值

    printf("Extracted age values:\n");
    printf("As integer: %d\n", age);
    printf("As double: %f\n", age_double);

    // 在这里可以使用age变量进行其他操作
  } else {
    printf("Warning: 'age' field not found or not a number\n");
  }

  // 4. 释放内存
  cJSON_Delete(json);

  return EXIT_SUCCESS;
}
